package com.shire.web.console.controller.kf;

import com.alibaba.fastjson.JSONObject;
import com.shire.web.console.common.DateUtil;
import com.shire.web.console.common.RandomGen;
import com.shire.web.console.common.Response;
import com.shire.web.console.dao.device.DeviceKeyDao;
import com.shire.web.console.model.device.DeviceKey;
import com.shire.web.console.model.device.DeviceKeyExample;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/device")
public class DeviceCodeController {
    @Resource
    private DeviceKeyDao deviceKeyDao;

    @RequestMapping("/list")
    @ResponseBody
    public Response listCodeForUser(Integer userId){
        Response response = new Response();
        try{
            DeviceKeyExample example = new DeviceKeyExample();
            example.createCriteria().andCompanyIdEqualTo(userId);
            example.setOrderByClause("realUdid desc");
            response.setData(deviceKeyDao.selectByExample(example));
            response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        return response;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Response update(@RequestBody DeviceKey key){
        Response response = new Response();
        try {
            deviceKeyDao.updateByPrimaryKeySelective(key);
            response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        return response;
    }

    @ResponseBody
    @RequestMapping("/createCodes")
    public Response createCodes(@RequestBody JSONObject jsonObject){
        Response response = new Response();
        try {
            List<DeviceKey> deviceKeys = new ArrayList<>();
            for (int i =0 ; i< jsonObject.getInteger("wxCount"); i++){
                DeviceKey key = new DeviceKey();
                key.setCompanyId(jsonObject.getInteger("id"));
                key.setCreateTime(new Date());
                key.setExpireDate(DateUtil.String2Date(jsonObject.getString("expireDate")));
                key.setStatus(0);
                key.setDeviceKey(RandomGen.getRandomLowerCase(8));
//                deviceKeyDao.insertSelective(key);
                deviceKeys.add(key);
            }

            deviceKeyDao.batchInsertSelective(deviceKeys);
            response.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        return response;
    }
}
